<template>
  <div class="sse-client">
    <h1 class="title">SSE 客户端</h1>
    <div class="message-container">
      <div class="message-box" ref="messageBox">
        <div v-for="(message, index) in messages" :key="index" class="message-item" :class="message.type">
          {{ message.text }}
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'SseClient',
  data() {
    return {
      source: null,
      userId: Math.random().toString(36).substr(2, 9),
      messages: []
    }
  },
  mounted() {
    this.initSSE()
  },
  beforeUnmount() {
    this.closeSSE()
  },
  methods: {
    initSSE() {
      if (window.EventSource) {
        this.source = new EventSource('http://localhost:8443/sse/connect?userId=' + this.userId)

        this.source.addEventListener('open', () => {
          console.log('建立连接成功...')
          this.addMessage('建立连接成功...', 'system')
        }, false)

        this.source.addEventListener('message', (e) => {
          this.addMessage(e.data, 'message')
        }, false)

        this.source.addEventListener('add', (e) => {
          this.addMessage(e.data, 'add')
        }, false)

        this.source.addEventListener('custom', (e) => {
          this.addMessage(`自定义事件：${e.data}`, 'custom')
        }, false)

        this.source.addEventListener('finish', () => {
          console.log('当前SSE事件推送完毕...')
        }, false)

        this.source.addEventListener('error', (e) => {
          if (e.target.readyState === EventSource.CLOSED) {
            console.log('连接已关闭...')
            this.addMessage('连接已关闭...', 'error')
          } else if (e.target.readyState === EventSource.CONNECTING) {
            console.error('CORS错误:', e)
            this.addMessage('跨域请求失败，请检查服务器CORS配置', 'error')
          } else {
            console.log('发生未知错误...')
          }
        })
      } else {
        console.log('您的浏览器不支持SSE')
        this.addMessage('您的浏览器不支持SSE', 'error')
      }
    },
    addMessage(text, type = 'message') {
      this.messages.push({ text, type })
      this.$nextTick(() => {
        if (this.$refs.messageBox) {
          this.$refs.messageBox.scrollTop = this.$refs.messageBox.scrollHeight
        }
      })
    },
    closeSSE() {
      if (this.source) {
        this.source.close()
      }
    }
  }
}
</script>

<style scoped>
.sse-client {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  font-family: Arial, sans-serif;
}

.title {
  color: #2c3e50;
  text-align: center;
  margin-bottom: 20px;
}

.message-container {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.message-box {
  height: 400px;
  overflow-y: auto;
  padding: 10px;
  background: white;
  border-radius: 4px;
  border: 1px solid #e9ecef;
}

.message-item {
  padding: 8px 12px;
  margin: 4px 0;
  border-radius: 4px;
  font-size: 14px;
  line-height: 1.4;
}

.system {
  background-color: #e3f2fd;
  color: #1976d2;
}

.message {
  background-color: #f1f8e9;
  color: #33691e;
}

.add {
  background-color: #f3e5f5;
  color: #7b1fa2;
}

.custom {
  background-color: #fff3e0;
  color: #e65100;
}

.error {
  background-color: #ffebee;
  color: #c62828;
}
</style>